﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Shoozla.View;
using Shoozla.DataModel;
using System.IO;
using System.Windows.Forms;
using System.Threading.Tasks;
using Shoozla.DataModel.Helper;
using MahApps.Metro.Controls;


namespace Shoozla.ViewModel
{
    /// <summary>
    /// The ViewModel for the application's main window.
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
        public event FolderAddedDelegate FolderAdded;
        public delegate void FolderAddedDelegate(DirectoryInfo folderName);

        #region Constructors

        public MainViewModel(Window view, Window owner) : base (view,owner)
        {           
            base.DisplayName = "Shoozla Main Window";
            CurrentView = App.FolderView;
        }

        #endregion // Constructor

        #region Commands       
       
        private RelayCommand _CmdClose;
        public RelayCommand CmdClose
        {
            get
            {
                if (_CmdClose == null)
                {
                    _CmdClose = new RelayCommand(param =>  System.Windows.Application.Current.Shutdown(), param => true);
                }
                return _CmdClose;
            }
        }
    
        private RelayCommand _CmdSave;
        public RelayCommand CmdSave
        {
            get
            {
                if (_CmdSave == null)
                {
                    _CmdSave = new RelayCommand(param => DoCmdSave(), param => {
                        if (!AppModel.IsAppWorking && AppModel.IsCollectionDirty()) return true;
                        else return false;
                        });
                }
                return _CmdSave;
            }
        }

        private RelayCommand _CmdSearch;
        public RelayCommand CmdSearch
        {
            get
            {
                if (_CmdSearch == null)
                {
                    _CmdSearch = new RelayCommand(param => DoCmdSearch(), param => CanExecuteSearch());
                }
                return _CmdSearch;
            }
        }

        private RelayCommand _CmdOpenFolder;
        public RelayCommand CmdOpenFolder
        {
            get
            {
                if (_CmdOpenFolder == null)
                {
                    _CmdOpenFolder = new RelayCommand(param => DoCmdOpenFolder(null), param => CanExecuteUI());
                }
                return _CmdOpenFolder;
            }
        }

        private RelayCommand _CmdAbout;
        public RelayCommand CmdAbout
        {
            get
            {
                if (_CmdAbout == null)
                {
                    _CmdAbout = new RelayCommand(param => DoCmdAbout(), param => { return true; });
                }
                return _CmdAbout;
            }
        }

        private RelayCommand _CmdOpenLog;
        public RelayCommand CmdOpenFLog
        {
            get
            {
                if (_CmdOpenLog == null)
                {
                    _CmdOpenLog = new RelayCommand(param => DoCmdOpenFLog(), param => { return true; });
                }
                return _CmdOpenLog;
            }
        }


        private DirectoryInfo _currentFolder;
        public DirectoryInfo CurrentFolder
        {
            get { return _currentFolder; }
            set {
                if (value != _currentFolder)
                {
                    _currentFolder = value;
                       ((FolderListViewModel)App.FolderView.DataContext).LoadMp3FromFolders(CurrentFolder); //display the files
                    OnPropertyChanged("CurrentFolder");                   
                }
            }
        }

        #endregion

        #region Do Commands

        private void DoCmdStopThreads()
        {
            AppModel.StopAllWork();
        }

        //NOTE Save all the modified mp3 files
        private void DoCmdSave()
        {
            AppModel.SaveCollection(View);                    
        }

        //NOTE Start the covers search
        private void DoCmdSearch()
        {                

            //it asks which "website" to use
            SearchAddinView saw = new SearchAddinView(AppModel.SelectedSongs.Count);
            var confirm = saw.ShowDialog();
            if (confirm != true)
                return;

            //start the internet search        
            AppModel.LogEntry("Connecting to " + AppModel.CoverSearcher.AddInName);

            if (AppModel.CoverSearcher.Initialize())
            {
                //clean the logging and everything else at each search
                AppModel.NotFoundMp3 = new List<Mp3File>();
                AppModel.CoverImageCache.Reset();
                AppModel.CoverSearcher.ClearCache();

                List<Mp3File> selected = AppModel.SelectedSongs.ToList<Mp3File>();
                AppModel.CoverSearcher.Songs = selected;

                //display UI
                AppModel.ProgressOperationQueue.Add(AppModel.CoverSearcher);
                AppModel.StartProgressBarInternal(AppModel.ProgressOperationQueue.ToList<IProgressOperation>());   
                
                //building the list of not found songs
                foreach (Mp3File m in AppModel.SelectedSongs)
                    if (m.ImageUrl == null)
                        AppModel.NotFoundMp3.Add(m);

                AppModel.ShowCoverPreviewWindow(); //display found covers

            }
            else
                MetroMessageBox.MetroShow(String.Empty, "Could not connect to the web service", true, App.MainView, MessageIcon.Error);
        }

        private void DoCmdOpenFLog()
        {
            App.Tracer.Flush();
            App.Tracer.Close();
            System.Diagnostics.Process.Start("notepad.exe", App.LogFileName);
        }

        private void DoCmdAbout()
        {
            AboutView aboutW = new AboutView(App.MainView);
            aboutW.ShowDialog();
        }
       
        public void DoCmdOpenFolder(DirectoryInfo dir)
        {
            if (dir == null)
            {
                //select new folder
                FolderBrowserDialog folderDialog = new FolderBrowserDialog();
                folderDialog.Description = "Select a folder with Mp3 files";
                var res = folderDialog.ShowDialog();
                if (res == DialogResult.OK)
                {
                    dir = new DirectoryInfo(folderDialog.SelectedPath);
                    CurrentFolder = dir;
                }
            }
            else
                //folder already selected, i.e: drag & drop
                CurrentFolder = dir;
                

          
        }
        #endregion

        private bool CanExecuteSearch()
        {
            if (!AppModel.IsAppWorking && AppModel.SelectedSongs.Count > 0)
                return true;
            else
                return false;
        }     
    }
}